package com.wenlin.myproduction.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.recyclerview.widget.RecyclerView;

import com.lxj.xpopup.XPopup;
import com.wenlin.myproduction.R;
import com.wenlin.myproduction.base.BaseActivity;
import com.wenlin.myproduction.base.BaseSwipeActivity;
import com.wenlin.myproduction.bean.InOutRecordBean;
import com.wenlin.myproduction.bean.InOutRecordsBean;
import com.wenlin.myproduction.binder.InOutRecordBinder;
import com.wenlin.myproduction.util.Checker;
import com.wenlin.myproduction.util.InOutDataManager;
import com.wenlin.myproduction.util.InOutUtil;
import com.wenlin.myproduction.util.MyGridLayoutManager;
import com.wenlin.myproduction.util.ToastUtils;
import com.wenlin.myproduction.util.UI;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * @desc: 借还列表页
 * @author: 文琳
 * @time: 2025/11/12 周三 16:14
 */
public class InOutActivity extends BaseSwipeActivity {
    private AppCompatCheckBox cbSearch;
    private EditText et;
    private TextView tvTotal, tvInput;
    private RecyclerView rv;
    private Items items;
    private MultiTypeAdapter adapter;
    private boolean searching;
    private boolean updating;
    private int updatePosition;

    public static void start(BaseActivity activity) {
        Intent intent = new Intent(activity, InOutActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public int getContentView() {
        return R.layout.activity_in_out_record;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("借还记录");
        //findViews
        rv = findViewById(R.id.rv);
        et = findViewById(R.id.et);
        cbSearch = findViewById(R.id.cb_search);
        tvTotal = findViewById(R.id.tv_total);
        tvInput = findViewById(R.id.tv_input);
        //init
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!searching) return;
                if (Checker.hasNoWord(UI.getEtText(et))) refreshData();
                else toDoAfterTextChanged(editable.toString());
            }
        });
        UI.setOnClickListener(tvTotal, v -> {
            if (items == null || items.isEmpty()) {
                ToastUtils.getInstance().showError("数据不够");
                return;
            }
            String first = "";
            Object o0 = items.get(items.size() - 1);
            if (o0 instanceof InOutRecordBean) {
                InOutRecordBean iorb = (InOutRecordBean) o0;
                first = iorb.getCreateTime();
            }
            float totalStart = 0f;
            List<InOutRecordBean> list = InOutDataManager.getList();
            for (int i = list.size() - 1; i >= 0; i--) {
                InOutRecordBean iorb = list.get(i);
                if (iorb.getCreateTime().equals(first)) break;
                float money = Float.parseFloat(iorb.getMoney());
                totalStart -= money;
            }
            List<InOutRecordBean> newList = new ArrayList<>();
            for (int i = items.size() - 1; i >= 0; i--) {
                Object o = items.get(i);
                if (o instanceof InOutRecordBean) {
                    InOutRecordBean iorb = (InOutRecordBean) o;
                    newList.add(iorb);
                }
            }
            InOutChartActivity.start(this, new InOutRecordsBean(newList, totalStart));
        });
        UI.setOnClickListener(tvInput, v -> {
            String str = UI.getEtText(et);
            if (Checker.hasNoWord(str)) {
                ToastUtils.getInstance().showInfo("请先输入");
                refreshData();
            } else {
                if (updating) updateRecord(str);
                else addRecord(str);
            }
        });
        UI.setOnClickListener(findViewById(R.id.iv_clear), v -> UI.setText(et, ""));
        cbSearch.setOnCheckedChangeListener((compoundButton, b) -> {
            searching = b;
            updateSearchUI();
        });
        items = new Items();
        adapter = new MultiTypeAdapter(items);
        adapter.register(InOutRecordBean.class, new InOutRecordBinder(bean -> {
            CommonDialog dialog = new CommonDialog(this).setTitle("操作")
                    .setContent("请选择需要的操作")
                    .setLeftText("删除")
                    .setLeftClickListener(view -> removeRecord(bean.getCreateTime()))
                    .setRightText("更新")
                    .setRightClickListener(view -> {
                        updating = true;
                        getUpdatePosition(bean);
                        String str = bean.getDate() + bean.getDesc() + bean.getMoney();
                        UI.setText(et, str);
                        UI.setSelection(et, str.length());
                    });
            new XPopup.Builder(this)
                    .asCustom(dialog)
                    .show();
        }));
        rv.setLayoutManager(new MyGridLayoutManager(this, 1));
        rv.setHasFixedSize(true);
        rv.setAdapter(adapter);

        initDataFromLocal();
    }

    /**
     * 如果没有数据则从本地文档中重置数据
     */
    private void initDataFromLocal() {
        if (InOutDataManager.getList().isEmpty()) {
            InputStream inputStream = getResources().openRawResource(R.raw.records);
            try {
                InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
                BufferedReader bufferedReader = new BufferedReader(reader);
                String line;
                while (true) {
                    line = bufferedReader.readLine();
                    if (line == null) break;
                    line = line.replaceAll("(\\t)+", "");//将空格过滤掉
                    InOutRecordBean bean = new InOutRecordBean(0, InOutUtil.getFormatCreateTime(), line.substring(0, 8), "", line.substring(8));
                    InOutDataManager.add(bean);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            CommonDialog dialog = new CommonDialog(this).setContent("已从文档中重载基础数据");
            new XPopup.Builder(this)
                    .asCustom(dialog)
                    .show();
        }
        refreshData();
    }

    /**
     * 更新数据并且更新价值文本
     */
    private void updateDataAndTotalStr(List<InOutRecordBean> list, String preString) {
        float total = 0f;
        float totalIn = 0f;
        float totalOut = 0f;
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setPosition(list.size() - 1 - i);
            float moneyWith100Times = Float.parseFloat(list.get(i).getMoney()) * 100;
            total += moneyWith100Times;
            if (moneyWith100Times < 0) totalOut += moneyWith100Times;
            else totalIn += moneyWith100Times;
        }
        String strTotal = (preString + total / 100).replaceAll("\\.0+$", "");
        String strIn = (" 收" + totalIn / 100).replaceAll("\\.0+$", "");
        String strOut = (" 支" + totalOut / 100).replaceAll("\\.0+$", "");
        UI.setText(tvTotal, strTotal + strIn + strOut);
    }

    /**
     * 从本地获取并刷新数据
     */
    private void refreshData() {
        List<InOutRecordBean> list = InOutDataManager.getList();
        updateListUI(list);
        updateDataAndTotalStr(list, "总额");
    }

    /**
     * 添加记录
     */
    private void addRecord(String str) {
        String[] arr = InOutUtil.getDateDescAndMoneyArrayByRegex(str);
        InOutDataManager.add(new InOutRecordBean(0, InOutUtil.getFormatCreateTime(), arr[0], arr[1], arr[2]));
        searching = false;
        UI.setText(et, "");
        refreshData();
    }

    /**
     * 移除记录
     */
    private void removeRecord(String createTime) {
        InOutDataManager.remove(createTime);
        refreshData();
    }

    /**
     * 更新记录
     */
    private void updateRecord(String str) {
        InOutDataManager.update(updatePosition, str);
        refreshData();
        UI.setText(et, "");
        updating = false;
    }

    /**
     * 获取更新的脚标
     */
    private void getUpdatePosition(InOutRecordBean record) {
        updatePosition = -1;
        List<InOutRecordBean> list = InOutDataManager.getList();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getCreateTime().equals(record.getCreateTime())) {
                updatePosition = i;
                break;
            }
        }
    }

    /**
     * 监听输入框文本，筛选内容显示在列表中并计算价值小计同步更新UI
     */
    private void toDoAfterTextChanged(String s) {
        List<InOutRecordBean> list = InOutDataManager.getList();
        List<InOutRecordBean> newList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            InOutRecordBean bean = list.get(i);
            if (s.equals("+")) {
                if (!bean.getMoney().contains("-")) newList.add(bean);
            } else {
                String str = "^" + bean.getDate() + bean.getDesc() + (bean.getMoney().contains("-") ? bean.getMoney() : "+") + bean.getMoney() + "$";
                if (str.toLowerCase(Locale.ROOT).contains(s.toLowerCase(Locale.ROOT)))
                    newList.add(bean);
            }
        }
        updateListUI(newList);
        updateDataAndTotalStr(newList, "总额小计");
    }

    private void updateListUI(List<InOutRecordBean> list) {
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setPosition((i + 1));
        }
        if (items != null) {
            if (!items.isEmpty()) {
                items.clear();
                adapter.notifyDataSetChanged();
            }
            items.addAll(list);
            adapter.notifyDataSetChanged();
        }
    }

    private void updateSearchUI() {
        if (searching) {
            String str = UI.getEtText(et);
            UI.setText(et, str);
            UI.setSelection(et, str.length());
        } else {
            refreshData();
        }
    }
}
